// 歌词部分

import { useStore } from 'vuex';
import { computed, watch, ref } from 'vue';
import { getLyric } from '@/service/song';
import Lyric from 'lyric-parser';

export default function useLyric({ songReady, currentTime }) {
  // 歌词解析组件实例
  const currentLyric = ref(null);
  // 当前显示行号
  const currentLineNum = ref(0);
  const lyricListRef = ref(null); // 歌词列表ref
  const lyricScrollRef = ref(null); // 滚动组件ref
  // 纯音乐标识
  const pureMusicLyric = ref('');
  // 当前播放歌词
  const playingLyric = ref('');

  const store = useStore();
  // 当前播放歌曲
  const currentSong = computed(() => store.getters.currentSong);
  watch(currentSong, async (newSong) => {
    // 判断歌曲是否合法
    if (!newSong.url || !newSong.id) {
      return;
    }
    // 切换歌曲之后前一个歌曲的歌词播放器还存在,和下一个会有冲突,会出现当前歌曲的歌词一直上下跳的情况
    // 需要先暂停,在清理上一首歌词,并初始化行号
    stopLyric();
    currentLyric.value = null;
    currentLineNum.value = 0;
    pureMusicLyric.value = '';
    playingLyric.value = '';

    const lyric = await getLyric(newSong);
    store.commit('addSongLyric', {
      song: newSong,
      lyric
    });
    // 如果当前歌曲歌词不等于获取的歌词,说明用户在连续点击(歌曲发生了快速切换),导致异步处理事件返回了不属于当前歌曲的数据
    if (currentSong.value.lyric !== lyric) {
      return;
    }

    currentLyric.value = new Lyric(lyric, handleLyric);
    // 有长度代表有歌词,否则为无歌词
    const hasLyric = currentLyric.value.lines.length;
    if (hasLyric) {
      // 当歌曲播放时,播放歌词,否则会被异步事件影响
      if (songReady.value) {
        playLyric();
      }
    } else {
      // 无歌词模式(纯音乐),将歌词前面的时间替换为空串
      // 如没有歌词,当前正在播放歌词是纯音乐模式文案
      playingLyric.value = pureMusicLyric.value = lyric.replace(/\[(\d{2}):(\d{2}):(\d{2})\]/g, '');
    }
    console.log(currentLyric, 999);
  });

  // 歌词播放
  function playLyric() {
    const currentLyricVal = currentLyric.value;
    if (currentLyricVal) {
      // seek组件库内部播放歌词方法,需要播放到当前时间
      currentLyricVal.seek(currentTime.value * 1000);
    }
  }

  // 歌词暂停播放
  function stopLyric() {
    const currentLyricVal = currentLyric.value;
    if (currentLyricVal) {
      // stop为歌词组件内部停止播放歌词方法
      currentLyricVal.stop();
    }
  }

  // 歌词处理
  // 当前方法为歌词播放器播放进度监听,当歌词暂停时,此方法将不会被触发
  function handleLyric({ lineNum, txt }) {
    // lineNum 行号
    // txt 当前正在播放歌词文案
    currentLineNum.value = lineNum;
    playingLyric.value = txt;
    const scrollComp = lyricScrollRef.value; // 歌词滚动组件实例
    const listEl = lyricListRef.value; // 歌词列表实例
    if (!listEl) {
      // 如果没有歌词列表则不需要处理滚动
      return;
    }
    if (lineNum > 5) {
      // 当前行号超过6条时,让滚动条开始滚动,保证高亮的歌词在中间
      const lineEl = listEl.children[lineNum - 5];
      // 滚动条滚动到对应DOM
      scrollComp.scroll.scrollToElement(lineEl, 1000);
    } else {
      scrollComp.scroll.scrollTo(0, 0, 1000);
    }
  }
  return {
    currentLyric,
    currentLineNum,
    lyricScrollRef,
    lyricListRef,
    pureMusicLyric,
    playingLyric,
    playLyric,
    stopLyric
  };
}
